 using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using XFControls.Utils;

namespace XDAFacebook
{
    public static class Settings
    {
        public static string settingsFileName = "\\XDAFacebookSettings.xml";
        public static string localizationDir = "\\localization";
        public static string SkinDir = "\\Skins";
        public static string blankLocFile = "blank";

        #region Application Settings

        public static string CurrentVersion = "4.8.9 BETA";

        public static string Skin = LocalizationStrings.Default;
        public static string Domain = "facebook";//"fa-ir.lisp4.facebook"; 
        //        		<add key="ApiKey" value="624687550958512"/>
        //		<add key="Secret" value="ff23b9fb92bdf3c87f4f204d6ff007ac"/>

        public static string appId = "624687550958512";     //"624687550958512";
        public static string appSecret = "ff23b9fb92bdf3c87f4f204d6ff007ac";    // "ff23b9fb92bdf3c87f4f204d6ff007ac";
        public static string language = "English";
        public static string auth_key = "";
        public static string ConnectionLosted = "No Connection Available";
        public static string pictureFileExtensions = ".gif,.jpg,.png,.bmp";
        public static bool ResizeImages { get { return WebDownloader.ResizeImages; } set { WebDownloader.ResizeImages = value; } }
        public static bool SaveDebug = false;
        public static int PhotosPerLine = 3;
        public static int ConcurrentDownload = 6;
        public static int IconSize = 45;
        public static int ImageSize = 70;
        public static int ExpanderHeight = 115;
        public static int ExpanderMax = 220;
        public static string FirstRun;
        public static int position = 1;
        public static bool useEmptyProxy { get { return WebDownloader.useEmptyProxy; } set { WebDownloader.useEmptyProxy = value; } }

        public static Dictionary<int, string> HomeIcons = new Dictionary<int, string>();

        private static string _homeIconString;
        #endregion

        #region Localization Strings

        public static class LocalizationStrings
        {
            public static string saveLogin = "Save Login";
            public static string login = "Login";
            public static string loginType = "Select your login type";
            public static string internLogin = "Internal";
            public static string internWebLogin = "Internal Web";
            public static string externWebLogin = "External Web";
            public static string userName = "User Name";
            public static string password = "Password";
            public static string clickToLogin = "Click Here to Login";
            public static string clickToLaunchBrowserInternal = "Click Here to Launch Internal WebBrowser";
            public static string clickToLaunchBrowserExternal = "Click Here to Launch External WebBrowser";
            public static string copyUrl = "Copy URL of \"Success\" page and click here";
            public static string copyUrlError = "Invalid URL String. Please try and copy again.";
            public static string browserMessage = "Once you see the screen that says \"Success\", copy the URL and click the button below";
            public static string AnotherInstance = "Another instance of XDAFacebook is already running.  Attempting to close all instances and restart.  If you see this message more than once, restart your device and try again.";
            public static string none = "None";
            public static string Name = "Name";
            public static string Description = "Description";
            public static string Mine = "Mine";
            public static string LoadMore = "Load More";
            public static string CantSendMessage = "3rd Pary APPs can't Compose Private Messages :'(";
            public static string Default = "Default";
            public static string Members = "Members";

            public static string createdSuccessfully = "Created Successfully!";
            public static string comingSoon = "Coming Soon";
            public static string Submit = "Submit";
            public static string Cancel = "Cancel";
            public static string Delete = "Delete";
            public static string Exit = "Exit";
            public static string logOut = "Log Out";
            public static string Menu = "Menu";
            public static string About = "About";
            public static string UploadPhotos = "Upload Photos";

            public static string photoUploadError = "There was an error uploading the photo";
            public static string photoUploadSuccess = "The photo was uploaded successfully";
            public static string uploadPhotosHeader = "Upload Photos";
            public static string choosePicture = "Choose your picture:";
            public static string noPicture = "(None)";
            public static string uploadPictureButton = "Click here to upload.";
            public static string percentImageUpload = "Percent of image complete";
            public static string pickAFile = "Please choose a file to upload";
            public static string fileUploading = "Your file is already uploading";
            public static string ErrorCreatingAlbum = "There was an error creating your album";
            public static string GiveAlbumName = "You must give a name to your album";
            public static string Subject = "Subject";
            public static string Message = "Message";
            public static string CompleteInfoNotes = "You must have text in the subject and message boxes";

            public static string Wall = "Wall";
            public static string Info = "Info";
            public static string Photos = "Photos";
            public static string noPosts = "No Posts";
            public static string noAlbums = "No Albums";

            public static string Home = "Home";
            public static string newsFeeds = "News Feed";
            public static string Profile = "Profile";
            public static string Friends = "Friends";
            public static string Inbox = "Inbox";
            public static string Chat = "Chat";
            public static string Requests = "Requests";
            public static string Events = "Events";
            public static string Notes = "Notes";
            public static string Places = "Places";
            public static string Checkin = "Checkin";
            public static string Albums = "Albums";
            public static string Groups = "Groups";
            public static string Calender = "Calender";
            public static string UpdateStatus = "Update Status";

            public static string dayAgo = "Day ago";
            public static string daysAgo = "Days ago";
            public static string hourAgo = "Hour ago";
            public static string hoursAgo = "Hours ago";
            public static string minAgo = "Minute ago";
            public static string minsAgo = "Minutes ago";
            public static string secAgo = "Second ago";
            public static string secsAgo = "Seconds ago";
            public static string momentsAgo = "Moments ago";
            public static string Comments = "Comments";
            public static string Comment = "Comment";
            public static string Likes = "Likes";
            public static string Like = "Like";
            public static string Unlike = "Unlike";
            public static string unlikePost = "Do you want to Unlike this post?";
            public static string likePost = "Do you want to Like this post?";

            public static string webLogin = "Web Login";
            public static string incorrectPassword = "Incorrect Email or Password";
            public static string serverTimeout = "There was a server Timeout.  make sure you have an internet connection";
            public static string unknownError = "There was an unknown error";
            public static string postingProblem = "There was a problem posting, try again?";
            public static string tryAgain = "Try Again";

            public static string AppOutOfDate = "Your app is out of date. Download latest version?";
            public static string outOfDate = "Out Of Date";
            public static string downloading = "Downloading file...";
            public static string downloadDone = "Download Done";
            public static string installNow = "Would you like to install it now?";
            public static string Install = "Install";

            public static string Loading = "Loading...";
            public static string AddComment = "Add Comment";
            public static string Compose = "Compose";
            public static string noStatus = "No status";
            public static string writeSomething = "Write something...";
            public static string createNewAlbum = "Create New Album";

            public static string basicInfo = "Basic Info";
            public static string Email = "Email";
            public static string gender = "Sex";
            public static string Birthday = "Birthday";
            public static string Hometown = "Hometown";
            public static string Relationship = "Relationship";
            public static string likesAndInterests = "Likes and Interests";
            public static string Activities = "Activities";
            public static string Interests = "Interests";
            public static string Music = "Music";
            public static string TV = "TV";
            public static string Movies = "Movies";
            public static string Books = "Books";
            public static string Quotes = "Quotes";
            public static string Bio = "Bio";

            public static string SelectFriend = "Select Friend Profile";
            public static string SearchFriends = "Search Friends";
            public static string NoFriends = "You have no friends :'(";
            public static string AddFriend = "Add Friends";
            public static string ClickFriendToRemove = "(Click on friends below to remove)";
            public static string TaggedFriends = "Tagged Friends:";

            public static string FilterPosts = "Filter Posts";
            public static string olderPosts = "Older Posts";
            public static string newerPosts = "Newer Posts";
            public static string olderLikes = "Older Likes";
            public static string newerLikes = "Newer Likes";
            public static string postDetailsHeaderTitle = "Post Details";
            public static string markAsRead = "Mark As Read";
            public static string notifications = "Notifications";
            public static string notificationsRead = "Old Notifications";
            public static string clearAll = "Clear All";
            public static string allNotificationsCleared = "Notifications cleared";

            public static string settings = "Settings";
            public static string resizeImages = "Resize Images before upload";
            public static string appSettingsHeader = "App Settings";
            public static string domainDescription = "Facebook Domain (ex: facebook)";
            public static string picExtDescription = "Picture File Extensions (Comma Separated)";
            public static string AppSkin = "Application Skin";
            public static string langDescription = "Select your language";
            public static string genBlankLangFile = "Generate Blank Language File";
            public static string restartApp = "You will need to restart the application for the changes to take effect";
            public static string position = "Get position by";
            public static string position_gps = "GPS";
            public static string position_both = "GPS + CellID";
            public static string position_cellID = "CellID";
            public static string proxy_settings = "Proxy Settings";
            public static string proxy_default = "default";
            public static string proxy_empty = "use empty proxy";

            public static string ErrorOccured = "An error has occurred and was logged. Please review and submit the file stored at: {0} to the dev team.  Thank you!";
            public static string FileNotExist = "The file does not exist.  Please PM this message to the developer on XDA-Developers. \"";
            public static string ErrorDeletingPost = @"There was an error deleting the post.  You can only delete posts made by XDAFacebook";
            public static string DeletePost = "Do you want to Delete this post?";
            public static string AndMoreUsers = "and {0} others.";
            public static string GettingGPS = "This may take a while.  GPS location data is being queried.";
            public static string GotGPS = "Found Location: {0}, {1}\nLoading results";
            public static string ErrorCheckingIn = "There was an error checking in";
            public static string LocalSearch = "Local Search:";
            public static string InvitedEvents = "Invited Events";
            public static string RespondedEvents = "Responded Events";

            public static string SearchInput = "Search Input:";
            public static string RequestType = "Results Type:";
            public static string PerformSearch = "Perform Search";

            public static string PreThreshold = "Keep pulling to refresh data";
            public static string PostThreshold = "Release to refresh data";

            public static string Location = "Location";
            public static string StartTime = "Start Time";
            public static string EndTime = "End Time";
            public static string RSVPStatus = "RSVP Status";
            public static string Owner = "Owner";
            public static string Version = "Version";
            public static string Privacy = "Privacy";
            public static string Online = "Online";
            public static string Status = "Status";
        }

        #endregion

        public static string GetCurrent_Directory()
        {
            return Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
        }

        public static bool ImportSettings()
        {
            if (XFGraphics.GetScreenResolution() == ScreenResolution.QVGA || XFGraphics.GetScreenResolution() == ScreenResolution.RotatedQVGA)
            {
                ExpanderMax /= 2;
                ExpanderHeight /= 2;
                IconSize /= 2;
                ImageSize /= 2;
            }
            if (File.Exists(settingsFileName))
            {
                try
                {

                    var settings = XDocument.Load(settingsFileName);

                    var t = typeof(Settings);
                    var ms = t.GetMembers();

                    foreach (var member in ms)
                    {
                        if (member.MemberType == MemberTypes.Field)
                            if (settings.Root.Descendants().Any(d => d.Name == member.Name))
                            {
                                string val = settings.Root.Descendants().First(d => d.Name == member.Name).Value;
                                var tm = ((FieldInfo)member).FieldType;
                                if (tm == typeof(string))
                                    ((FieldInfo)member).SetValue(null, val);
                                else if (tm == HomeIcons.GetType())
                                    _homeIconString = val;
                                else
                                    ((FieldInfo)member).SetValue(null, Convert.ChangeType(val, tm, null));
                            }
                    }

                    if (settings.Root.Descendants("useEmptyProxy").FirstOrDefault() != null)
                        useEmptyProxy = Boolean.Parse(settings.Root.Descendants("useEmptyProxy").FirstOrDefault().Value);
                    ResizeImages = Boolean.Parse(settings.Root.Descendants("ResizeImages").FirstOrDefault().Value);

                    if (!string.IsNullOrEmpty(_homeIconString))
                        HomeIcons.Deserialize(_homeIconString);

                    if (!string.IsNullOrEmpty(auth_key))
                        auth_key = auth_key.Decrypt();

                    if (Directory.Exists(localizationDir))
                    {
                        foreach (var file in Directory.GetFiles(localizationDir))
                        {
                            if (file.Contains(language))
                                importLanguage(file);
                        }
                    }
                    return true;

                }
                catch (Exception) { }
            }
            return false;
        }

        public static void SaveSettings()
        {
            XDocument settings;
            if (File.Exists(settingsFileName))
                settings = XDocument.Load(settingsFileName);
            else
                settings = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XElement("settings",
                        new XElement("email"),
                        new XElement("auth_key")));

            if (settings.Root.Descendants("Domain").Any())
                settings.Root.Element("Domain").Value = Domain;
            else
                settings.Root.Add(new XElement("Domain", Domain));

            if (settings.Root.Descendants("position").Any())
                settings.Root.Element("position").Value = position.ToString();
            else
                settings.Root.Add(new XElement("position", position.ToString()));

            if (settings.Root.Descendants("useEmptyProxy").Any())
                settings.Root.Element("useEmptyProxy").Value = useEmptyProxy.ToString();
            else
                settings.Root.Add(new XElement("useEmptyProxy", useEmptyProxy.ToString()));

            if (settings.Root.Descendants("Skin").Any())
                settings.Root.Element("Skin").Value = Skin;
            else
                settings.Root.Add(new XElement("Skin", Skin));

            if (settings.Root.Descendants("language").Any())
                settings.Root.Element("language").Value = language;
            else
                settings.Root.Add(new XElement("language", language));

            if (settings.Root.Descendants("pictureFileExtensions").Any())
                settings.Root.Element("pictureFileExtensions").Value = pictureFileExtensions;
            else
                settings.Root.Add(new XElement("pictureFileExtensions", pictureFileExtensions));

            if (settings.Root.Descendants("ResizeImages").Any())
                settings.Root.Element("ResizeImages").Value = ResizeImages.ToString();
            else
                settings.Root.Add(new XElement("ResizeImages", ResizeImages.ToString()));

            if (settings.Root.Descendants("PhotosPerLine").Any())
                settings.Root.Element("PhotosPerLine").Value = PhotosPerLine.ToString();
            else
                settings.Root.Add(new XElement("PhotosPerLine", PhotosPerLine.ToString()));

            if (settings.Root.Descendants("ConcurrentDownload").Any())
                settings.Root.Element("ConcurrentDownload").Value = ConcurrentDownload.ToString();
            else
                settings.Root.Add(new XElement("ConcurrentDownload", ConcurrentDownload.ToString()));

            if (!string.IsNullOrEmpty(FirstRun))
            {
                if (settings.Root.Descendants("FirstRun").Any())
                    settings.Root.Element("FirstRun").Value = FirstRun;
                else
                    settings.Root.Add(new XElement("FirstRun", FirstRun));
            }

            if (settings.Root.Descendants("HomeIcons").Any())
                settings.Root.Element("HomeIcons").Value = HomeIcons.Serialize();
            else
                settings.Root.Add(new XElement("HomeIcons", HomeIcons.Serialize()));

            settings.Save(settingsFileName);
        }

        private static void importLanguage(string file)
        {
            Dictionary<string, string> lang = new Dictionary<string, string>();
            using (StreamReader sr = new StreamReader(file, Encoding.Default))
            {
                Regex reg = new Regex("(?<key>.*?)\\s*=\\s*\"(?<value>.*?)\"");
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    if (!reg.IsMatch(line))
                        continue;

                    Match m = reg.Match(line);

                    string key = m.Groups["key"].Value;
                    string value = m.Groups["value"].Value;

                    lang.Add(key, value);
                }
            }

            var t = typeof(LocalizationStrings);
            var ms = t.GetMembers();

            foreach (var member in ms)
            {
                if (member.MemberType == MemberTypes.Field)
                    if (lang.ContainsKey(member.Name))
                        ((FieldInfo)member).SetValue(null, lang[member.Name]);
            }
        }

        public static void SaveBlankLang()
        {
            StringBuilder sb = new StringBuilder();
            var t = typeof(Settings.LocalizationStrings);
            var ms = t.GetMembers();

            foreach (var member in ms)
            {
                if (member.MemberType == MemberTypes.Field)
                {
                    sb.AppendLine(member.Name + " = \"" + ((FieldInfo)member).GetValue(null) + "\"");
                }
            }

            using (StreamWriter outfile = new StreamWriter(localizationDir + "\\" + blankLocFile + ".txt"))
            {
                outfile.Write(sb.ToString());
            }
        }

        public static string Serialize(this Dictionary<int, string> dict)
        {
            string ret = "";

            foreach (var itm in dict)
                ret += itm.Key + "," + itm.Value + ";";
            return ret;
        }

        public static void Deserialize(this Dictionary<int, string> dict, string val)
        {
            foreach (var s in val.Split(';'))
            {
                if (string.IsNullOrEmpty(s)) continue;

                int key = int.Parse(s.Split(',')[0]);
                if (!dict.ContainsKey(key))
                    dict.Add(key, s.Split(',')[1]);
            }
        }
    }
}
